package com.example.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件处理工具
 *
 * @email: pengyujun53@163.com
 * @author: peng_YuJun
 * @date: 2023/3/11
 * @time: 17:36
 */
@Slf4j
public class FileUtil {

    /**
     * 获取文件
     *
     * @param fileName
     * @param folderPath
     * @return
     * @throws Exception
     */
    public static Resource loadFileAsResource(String folderPath, String fileName) throws Exception {
        try {
            Path filePath = Paths.get(folderPath).resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()) {
                return resource;
            } else {
                log.warn("File not found " + fileName);
            }
        } catch (MalformedURLException ex) {
            log.error("File not found " + fileName, ex);
        }
        return null;
    }

    /**
     * 存文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String storeFile(MultipartFile file, String fileDir, boolean isKeepName) {
        // Normalize file name
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        if (!isKeepName) { //不保持文件名
            fileName = randomFileName(fileName);
        }
        //store file
        try {
            File targetFile = new File(fileDir);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            File targetFileName = new File(targetFile, fileName);
            file.transferTo(targetFileName);
        } catch (IOException e) {
            log.error("File can't store " + fileName, e);
            return null;
        }
        return fileName;
    }

    /**
     * 将文本内容存入文件
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String writeTextFile(String content, String fileDir, boolean isKeepName, String fileName) {
        // file name
        if (!StringUtils.hasText(fileName)) {
            fileName = RandomGUID.getRandomGUID() + ".html";
        }
        //store file
        try {
            //获取或创建文件
            File targetFile = new File(fileDir);
            if (!targetFile.exists()) {
                targetFile.mkdirs();//创建父路径
            }
            File targetFileName = new File(targetFile, fileName);
            //写入
            PrintWriter pw = new PrintWriter(new FileOutputStream(targetFileName));
            pw.println(content);
            //pw.append(content); //这是追加
            pw.close();
        } catch (IOException e) {
            log.error("txtFile can't write " + fileName, e);
            return null;
        }
        return fileName;
    }

    /**
     * 将文本内容存入文件
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String readTextFile(String folderPath, String fileName) {
        String content = null;
        try {
            Path filePath = Paths.get(folderPath).resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()) {
                byte[] bytes = new byte[0];
                bytes = Files.readAllBytes(filePath);
                content = new String(bytes, StandardCharsets.UTF_8);
            } else {
                log.error("txtFile can't found " + fileName);
            }
        } catch (IOException e) {
            log.error("txtFile can't read " + fileName, e);
        }
        return content;
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @param folderPath
     */
    public static void deleteFile(String folderPath, String fileName) {
        File file = new File(folderPath + fileName);
        file.delete();
    }

    /**
     * 生成随机的文件名
     *
     * @return
     */
    public static String randomFileName(String filePath) {
        String fileExtension = getFileExtension(filePath);
        return RandomGUID.getRandomGUID() + "." + fileExtension;
    }


    /**
     * 获取全路径中的文件拓展名
     *
     * @param filePath 文件路径
     * @return 文件拓展名
     */
    public static String getFileExtension(final String filePath) {
        if (!StringUtils.hasText(filePath)) return filePath;
        int lastPoi = filePath.lastIndexOf('.');
        int lastSep = filePath.lastIndexOf(File.separator);
        if (lastPoi == -1 || lastSep >= lastPoi) return "";
        return filePath.substring(lastPoi + 1);
    }

    /**
     * 获取apk的大小【单位：KB】
     *
     * @param file 文件
     * @return 文件长度
     */
    public static int getApkFileSize(final File file) {
        long fileLength = getFileLength(file);
        return (int) (fileLength / 1024);
    }

    /**
     * 获取文件长度
     *
     * @param file 文件
     * @return 文件长度
     */
    public static long getFileLength(final File file) {
        if (!isFile(file)) return -1;
        return file.length();
    }

    /**
     * 判断是否是文件
     *
     * @param file 文件
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isFile(final File file) {
        return file != null && file.exists() && file.isFile();
    }

    /**
     * 判断是否MultipartFile
     *
     * @param file
     * @return {@code true}: 是<br>{@code false}: 否
     */
    public static boolean isMultipartFile(final MultipartFile file) {
        return file != null && !file.isEmpty() && file.getSize() > 0;
    }
}
